package cn.joeg.dp.singleton.register;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by CQ on 2018/3/7.
 */

//类似Spring里的方法，将类名注册，下次从里面直接取
//spring ioc 容器的做法
//注册登记式，默认的ID式类名首字母小写
public class RegisterSingleton2 {

    private static Map<String, RegisterSingleton2> register = new HashMap<>();

    static {
        RegisterSingleton2 single = new RegisterSingleton2();
        register.put(single.getClass().getName(), single);
    }

    private RegisterSingleton2() {}

    public static RegisterSingleton2 getInstance(String name) {
        if (name == null) {
            name = RegisterSingleton2.class.getName();
        }

        if (register.get(name) == null) {
            try {
                register.put(name, (RegisterSingleton2) Class.forName(name).newInstance());
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return register.get(name);
    }
}
